/**
 * 
 */
package com.sn.core.util;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author guozw@github.com/xingganfengxing/
 *
 */
public class ObjectUtils {
	
	public static Map<String, String> getDeclaredFields(Object obj) {
		Map<String, String> rt = new HashMap<String, String>();
		// 获取对象obj的所有属性域
		Field[] fields = obj.getClass().getDeclaredFields();
		return getDeclaredFields(obj, fields);
	}
	
	public static Map<String, String> getDeclaredFields(Object obj, Field[] fields) {
		Map<String, String> rt = new HashMap<String, String>();

		for (Field field : fields) {
			// 对于每个属性，获取属性名
			String key = field.getName();
			if("serialVersionUID".equals(key) || "DEFAULT_INITIAL_CAPACITY".equals(key)) {
				continue;
			}
			try {
				
				boolean access = field.isAccessible();
				if (!access) {
					field.setAccessible(true);
				}
				
				// 从obj中获取field变量
				Object value = field.get(obj);
				if(value != null) {
					String pval = "";
					if(value instanceof String || value instanceof Integer || value instanceof Float
							|| value instanceof Short || value instanceof Long || value instanceof Double) {
						pval = value.toString();
					} else if(value instanceof Boolean) {
						if((Boolean)value) {
							pval = "1";
						} else {
							pval = "0";
						}
					}
					if(StringUtils.isNotBlank(pval)) {						
						rt.put(key, pval);
					}
				}

				if (!access){
					field.setAccessible(false);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return rt;
	}
	
	public static class Test{
		private String name;
		private String email;
		private int age;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getEmail() {
			return email;
		}
		public void setEmail(String email) {
			this.email = email;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
	}
	
	public static void main(String[] args) {
		Test t = new Test();
		t.setName("韩梅梅");
		t.setEmail("1@qq.com");
		t.setAge(30);
		
		Long a = 2323l;
		System.out.println(a.toString());
		
//		Map<String, String> rt = getDeclaredFields(t);
//		for(String k : rt.keySet()) {
//			String fmt = "key=%s,value=%s";
//			System.out.println(String.format(fmt, k, rt.get(k)));
//		}
		
	}

}
